package web

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"net/http/httputil"
	"net/url"
	"proxy/clientIP"
	"proxy/common"
	"proxy/hosts"
)

func update(writer http.ResponseWriter, request *http.Request) {
	IP := clientIP.RemoteIP(request)
	req := request.URL.String()

	response := make(chan string)
	msg := hosts.SignalUpdateObject{IP: IP, Req: req, Response: response}
	hosts.ChanOfUpdate <- msg

	_, err := io.WriteString(writer, <-response)
	if err != nil {
		logrus.Error(err)
		return
	}
}

func reverseProxy(writer http.ResponseWriter, request *http.Request) {
	response := make(chan string)
	msg := hosts.SignalProxyObject{Response: response}
	hosts.ChanOfLoadBalance <- msg

	Url := <-response
	targetURL, err := url.Parse(Url)
	if err != nil {
		logrus.Error(err)
		return
	}
	logrus.Info("选中的服务是：", Url)

	proxy := httputil.NewSingleHostReverseProxy(targetURL)
	proxy.ServeHTTP(writer, request)
}

func ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	method := request.Method
	req := request.URL.String()

	s := fmt.Sprintf("[ip: %s, Method: %s, req: %s]", clientIP.RemoteIP(request), method, req)
	common.GreenPrintln(s)

	if "GET" == method { //处理更新请求
		if "/U" == req || "/D" == req {
			update(writer, request)
			return
		}
	}
	reverseProxy(writer, request) //处理postman请求
}

func run(port int) {
	s := fmt.Sprintf("服务器启动中，监听端口%d....", port)
	common.BluePrintln(s)

	http.HandleFunc("/", ServeHTTP)

	addr := fmt.Sprintf(":%d", port)
	logrus.Fatal(http.ListenAndServe(addr, nil))
}

func Run() {
	hosts.Loading()
	run(8060)
}
